package qeug.shsh.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;

import java.util.Collections;
import java.util.EventObject;
import java.util.Map;

//行程信息分录编辑页：一级承担部门字段逻辑
public class tripEntryEditBillPlugin extends AbstractFormPlugin {

    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        DynamicObject costDept = (DynamicObject) this.getModel().getValue("entrycostdept");//费用承担部门
        DynamicObject orgPattern = costDept.getDynamicObject("orgpattern");
        if (orgPattern == null) {
            return;
        }
        String orgPatternNumber = orgPattern.getString("number");
        if (!orgPatternNumber.equals("Orgform06")) {
            //填写的费用承担部门的形态不是部门时，直接将费用承担部门值赋值给一级承担部门
            this.getModel().setValue("qeug_costdept", costDept);//一级承担部门
            return;
        }

        DynamicObject currentOrg = costDept;//当前部门
        DynamicObject topLevelDept = null;//最上级部门

        while (true) {
            long currentOrgId = Long.parseLong(currentOrg.getString("id"));//当前部门ID
            Map<Long, Long> orgParentMap = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.Admin, Collections.singletonList(currentOrgId));//获取当前部门的上级组织
            Long parentId = orgParentMap.get(currentOrgId);//上级组织ID
            if (parentId == null) {
                // 没有上级组织，当前组织就是最顶级组织
                topLevelDept = currentOrg;
                break;
            }

            DynamicObject parentOrg = BusinessDataServiceHelper.loadSingle("bos_adminorg",
                    new QFilter[]{new QFilter("id", QCP.equals, parentId)});//行政组织-上级组织

            if (parentOrg != null) {
                DynamicObject parentOrgPattern = parentOrg.getDynamicObject("orgpattern");//组织形态
                if (parentOrgPattern != null) {
                    String parentOrgPatternNumber = parentOrgPattern.getString("number");//组织形态编号
                    if (!parentOrgPatternNumber.equals("Orgform06")) {
                        // 上级组织不是部门类型，当前组织即为一级承担部门
                        topLevelDept = currentOrg;
                        break;
                    }
                }
                currentOrg = parentOrg;
            } else {
                // 无法加载上级组织，当前组织为最顶级
                topLevelDept = currentOrg;
                break;
            }
        }

        this.getModel().setValue("qeug_costdept", topLevelDept);//一级承担部门
    }
}
